
/******************************************************************************************
*******************************************************************************************
**                                                                                       **
**  GVAR Forecasting  (30 July 2009)                                                     **
**                                                                                       **
**                                                                                       **
**  This code was written by L. Vanessa Smith. Please address any questions, comments    **
**  or bugs to: lvs21@cam.ac.uk                                                          **       
**                                                                                       **
**  The code replicates the results in:                                                  **
**                                                                                       **
**    M. Hashem Pesaran, Til Schuermann and L. Vanessa Smith (2009),			 **
**                     									 **  
**   "Forecasting Economic and Financial Variables with Global VARs",                    **
**   International Journal of Forecasting, forthcoming.                    		 **
**                                                                                       **
**      and is based on the papers by:                                                   **
**                                                                                       ** 
**   1. Stephane Dees, Filippo di Mauro, M. Hashem Pesaran and L. Vanessa Smith (2007)   ** 
**     											 **
**     "Exploring the International Linkages of the Euro Area: A Global VAR Analysis",   **                                                            
**     Journal of Applied Econometrics 22, 1-38. 					 **
**						 					 **	
** 											 **
**   2. Stephane Dees, Sean Holly, M. Hashem Pesaran and L. Vanessa Smith (2007) 	 **
**         										 **
**     "Long Run Macroeconomic Relations in the Global Economy",			 **
**     Economics - The Open-Access, Open-Assessment E-Journal, 2007-3.          	 **  
**                                                                                       **                                                           
**                                                                                       **                                               
*******************************************************************************************
******************************************************************************************/



new 2000, 128000;

library gvarlb2005Q4,gvarlbForc,pgraph;

format /ld 7,14;

d1=date;


ccut=0.25; @ Percentage of trimming for the structural stability chow test
              for the country-specific VARX* models @

/** The country codes for which over-identified restrictions are imposed.
 The correspoding country names are: 
China,Euro Area,Japan,Australia,Canada,Norway,Sweden,Switzerland,UK,US
This is not relevant for the results in DdPS (2007)**/

ccOR={160,86,158,193,156,196,142,144,146,112,110}; 


gname1 = "c:\\gauss6.0\\gvar\\ImportFiles\\regcountry.xls";   
range1 = "b2:c34";
indxreg = xlsreadm(gname1, range1, 1, "");   


gname1 = "c:\\gauss6.0\\gvar\\ImportFiles\\regcountry.xls"; 
range2 = "a2:a34";
cnamd = xlsreadsa(gname1, range2, 1, "");

indnumcr=uniqindxstr(cnamd);
cnam=cnamd[indnumcr];


/** Trade - Matrix ***/

gname2 = "c:\\gauss6.0\\gvar\\ImportFiles\\tradematrix8005.xls";   
range2 = "a2:ai859";                                               
trdmtx = xlsreadm(gname2, range2, 1, "");   


/*** PPP-GDP data over three years 1999-2001, for all countries (33 countries) ***/

gname2 = "c:\\gauss6.0\\gvar\\ImportFiles\\pppgdp9901.xls"; 
range2 = "b2:d34";    
pppgdp = xlsreadm(gname2, range2, 1,"");

/*** PPP-GDP data over three years 1999-2001, for all countries/regions (26 countries/regions) ***/

gname2 = "c:\\gauss6.0\\gvar\\ImportFiles\\pppgdp9901_reg.xls";   
range2 = "b2:d27";
pppgdp_reg = xlsreadm(gname2, range2, 1, "");


/*** country/regional codes that follow the order of the PPP-GDP data given in pppgdp9901_reg **/ 

gname3 = "c:\\gauss6.0\\gvar\\ImportFiles\\idpppgdp9901_reg.xls";  
range3 = "b2:b27";
idrg = xlsreadm(gname3, range3, 1, "");



ypp=idrg~pppgdp_reg;  



/***** PPP-GDP weights plus regions for impulse responses etc ****/ 

gname1 = "c:\\gauss6.0\\gvar\\ImportFiles\\indxregcir_reg.xls";
range1 = "a2:b27";
indxregcir = xlsreadm(gname1, range1, 1, "");

rgcode=indxregcir[.,2]'; 


gname3 = "c:\\gauss6.0\\gvar\\ImportFiles\\EuroDollarRate2000.xls";
range3 = "b2:b5";    
eausfx = xlsreadm(gname3, range3, 1, "");


gname = "c:\\gauss6.0\\gvar\\ImportFiles\\OveridRestrictions.xls";
range = "a3:b63";   
hdOR_epepsus = xlsreadsa(gname, range, 1, ""); 

gname = "c:\\gauss6.0\\gvar\\ImportFiles\\OveridRestrictions.xls";
range = "d3:e62";   
hdOR_epeps = xlsreadsa(gname, range, 1, "");

/**********************************/

/*** This information corresponds to the data in the countries33_2005Q4 file
 within the Import Folder irrespective of the data that one ends up using 
for estimation ***/ 

nyrs_rwin=3;
startdate_prd=1979;
startdate_trdmtx=1980;
findate=2005;
yr_sq=seqa(1979,1,findate-startdate_prd+1);
numbreg=maxc(indxreg[.,1]);
qini=1;  /*** initial quarter ***/
qfin=4; /*** final quarter ***/
frq=4; /*** frequency quarterly ***/
cvecea={122,124,172,132,134,136,138,184}; /** Country codes that form the euro area **/
baseyear=2000; /** baseyear to convert FXdol rates of euro area countries to an index **/

cs=3;  /*** Case for cointegration: Unrestricted intercepts no trend ***/


cs_id1=cs*ones(rows(cnam),1);


yr_sq_org=yr_sq;


/********************************************************/


/** 33 countries **/

fname1 = "c:\\gauss6.0\\gvar\\ImportFiles\\countrydata33_2005Q4.xls"; 
fname3 = "c:\\gauss6.0\\gvar\\ImportFiles\\countrycodes.xls";

range1 = "b2:h109"; 
range3 = "b2:b34";


cc = xlsreadm(fname3, range3, 1, "");


N=rows(cc);
 id1_call=cc;  /**country codes **/        

cini = xlsreadm(fname1, range1, 1, "");


/* Set-up for parameters */
  T  = rows(cini);   @Number of observations@ 
  k   = 6;   @Number of endogenous variables, excluding variables such as oil, 
              which are endogenous to some countries and exogenous to others@
  kst = k;   @Number of foreign(star) variables, excluding variables such as oil, 
              which are endogenous to some countries and exogenous to others@
  ex  = 1;   @Number of exogenous variables other than foreign(star) variables, i.e oil@
/*======================================================================*/



namvri=seqa(11,1,k);   

@--- The below implies that the data is imported with the "exogenous" variables added to the end ----@

if ex/=0;
sqex=seqa(30,1,ex);
namvri=namvri|sqex;
vcex=namvri[rows(namvri)-ex+1:rows(namvri)];
else;
vcex=ex;
endif;  


/****** converts to ln ******/

i=1;
do while i<=N;

sheet=i;

cindv = xlsreadm(fname1, range1, sheet, "");

{cln}=convertlnnew(cindv,namvri);

if i==1;
c=cln;
elseif i>1;
c=c|cln;
endif;

i=i+1;
endo;


/**** add a column with the corresponding index next to each country in c ****/

v=zeros(N*T,1);

i=1;
do while i<=N;
j=1;
do while j<=T;
v[(i-1)*T+j]=id1_call[i];
j=j+1;
endo;
i=i+1;
endo;

xwex=v~c;


x=v~c[.,1:k];  


/***if pppgdp does not have the same order as the country codes  
these are repositioned in order to match **/


{rgcwgts}=ppp_regional_weights(id1_call,pppgdp,indxreg);  


/*** The ordering of the constructed regional domestic variables 
is that specified for the regions. The rgcodes follow also the 
ordering of the regions ***/

{xrg_plus_oil}=regional_variables_plus_oil(rgcode,indxreg,rgcwgts,k,x,T,xwex,ex,namvri,eausfx,
                                              frq,qini,qfin,yr_sq,cvecea,baseyear);  /*** first column of regional x  
                                                                                                   has the country/region code ****/

x=xrg_plus_oil;

/*******************/

/***  reset k and kst now that oil has been appended to regional variables**/

k=k+ex;
kst=k;

/***** regional share matrix *****/

N=cols(rgcode);
id1=rgcode';  

/*******************/


/***** For in sample estimation the avergage of the trade weights over the three year period 1999-2001 are used. 
Later on to compute the 2004 forecasts the average of the trade weights over the three year period 2001-2003 is used,
to compute the 2005 forecasts the average over the period 2002-2004 is used and to compute the 2006 forecasts the 
average over the period 2003-2005 is used **/ 

{rgshmtx_allyrs,rgshmtx1_allyrs,rgshmtx_yall_cind}=TradeMatrixAverages(rgcode,indxreg,nyrs_rwin,startdate_trdmtx,yr_sq,numbreg,trdmtx);

rgshmtx_allyrs_org=rgshmtx_allyrs;


datey=vec(reshape(yr_sq,frq,rows(yr_sq)));
numbforq=reshape(seqa(1,1,frq),frq*rows(yr_sq),1);
yqrts=("" $+ ftocv(datey,1,0))$+"Q"$+("" $+ ftocv(numbforq,1,0));
yqrts=yqrts[qini:rows(yqrts)-(frq-qfin)];
yqrtnumb=datey~numbforq;
yqrtnumb=trimr(yqrtnumb,qini-1,frq-qfin);
yqrts1=("" $+ ftocv(datey,1,0))$+"0"$+("" $+ ftocv(numbforq,1,0));
yqrts2=strtof(yqrts1);  /*** converts string to matrix ***/
yqrts2tr=trimr(yqrts2,qini-1,frq-qfin);


type_win=1; /*** expanding window ***/

{binend}=construction_binend(id1,namvri,x);


/*** Ordering specified for the forecasting output ***/

let string cnamforc={"US","EuroArea","China","Japan","UK","Canada","Australia","Sweden","Switzerland","Norway",
"NewZealand","Argentina", "Brazil", "Chile", "Mexico", "Peru", "Indonesia",
"Korea","Malaysia","Philippines","Singapore","Thailand","India",
"SAfrica","SaudiArabia","Turkey"};


/*** Changes the ordering of the countries based on the ordering below ***/

id1forc={110,86,160,158,112,156,193,144,146,142,196,213,223,228,273,293,536,542,548,566,576,578,534,199,456,186};




/***************************/

type_fx=1; /** If type_fx=0: use the nominal exchange rate
               If type_fx=1: use the real exchange rate  **/

/*** The variables used as initial values for forecasting ***/
/** We don't need to use  type_fx because e-p is always forcasted in the GVAR **/
{cvxt_trUSpr_ini,cvxt_trALLpr_ini}=cvxtr_proc_ini(id1,namvri,x);

/*** Actual data used for RMSE **********/

{cvxt_trUSinfl,cvxt_trUSinflFD}=cvxtr_proc(id1,namvri,x,type_fx);


/****************************************/

/*** Repositioning the actual data to follow the ordering 
of the countries as set out above for the purpose of 
showing the output ***/

{cvxt_trUSinfl_rep}=reposition(id1forc,cvxt_trUSinfl,1);
{cvxt_trUSinfl_callvind}=callvindforc(namvri,cvxt_trUSinfl_rep,1);


numbBM=4; /** Number of benchmark models: AR(1) constant, AR(1) const&trend,  Random Walk (RW) with no drift, RW with drift ***/


let string modname={"DdPS-GVAR","DdPS-GVAR_r=0","DdPS-GVAR_r=0_(1,1)","DdPS-GVAR_r=0_(1,2)","DdPS-GVAR_r=0_(2,1)",
"DdPS-GVAR_r=0_(2,2)","DdPS-GVAR11_rest_r=0_(1,1)","DdPS-GVAR11_rest_r=0_(1,2)","DdPS-GVAR11_rest_r=0_(2,1)","DdPS-GVAR11_rest_r=0_(2,2)","DHPS-GVAR",
"DHPS-GVAR_r=0_(1,1)","DHPS-GVAR_r=0_(1,2)","DHPS-GVAR_r=0_(2,1)","DHPS-GVAR_r=0_(2,2)","DHPS-GVAR11_rest_r=0_(1,1)","DHPS-GVAR11_rest_r=0_(1,2)",
"DHPS-GVAR11_rest_r=0_(2,1)","DHPS-GVAR11_rest_r=0_(2,2)"};

filepath = "c:\\gauss6.0\\gvar\\ImportFiles\\Models19_DdPS-GVAR&DHPS-GVAR.xls";


NumbExp=xlsGetSheetCount(filepath);



/**** Starting Dates for Expanding Window ****/ 


BeginDates={"1979Q1","1979Q2","1979Q3","1979Q4","1980Q1","1980Q2","1980Q3","1980Q4","1981Q1","1981Q2"};

/****************************************/


xorg=x;

enddatef="2003Q4"; /*** End date of the in-sample estimation window **/


yyd2= yqrts[.,1] .$== enddatef;


/**********************/

fhorzorg=rows(yyd2)-indexcat(yyd2,1);
csumfhorz=cumsumc(seqa(1,1,fhorzorg));
rnumb=sumc(sumc(binend[.,2:cols(binend)]))*csumfhorz[rows(csumfhorz)];

cnumb=5+1+rows(BeginDates); /** 5 columns give the information/ 1 gives the actual data/the rest give the forecast **/


marray = arrayinit((NumbExp+numbBM)|rnumb|cnumb,-9999);
marraysign1 = arrayinit((NumbExp+numbBM)|rnumb|cnumb,-9999);
marraysign2 = arrayinit((NumbExp+numbBM)|rnumb|cnumb,-9999);

 indij=0;

range = {"b3:f28"}; 
modelinput1 = xlsreadm(filepath, range, 1, "");

Lv_1=modelinput1[.,1];
Lvst_1=modelinput1[.,2];
rcnt_1=modelinput1[.,3];
type_idbeta_1=packr(modelinput1[.,4]);
type_restr_1=packr(modelinput1[.,5]);

sqij=seqa(1,1,(NumbExp+numbBM));


ij=1;
do while ij<=(NumbExp+numbBM); 

       indij= indij|ij;
fname ="c:\\gauss6.0\\gvar\\output\\forecast\\#models.xls";
ret = xlsWrite(indij, fname,"a2",1,"");

sheet=ij;

if ij>NumbExp; 
Lv=Lv_1; Lvst=Lvst_1; rcnt=rcnt_1; type_idbeta=type_idbeta_1;
type_restr=type_restr_1;

else;
range = {"b3:f28"}; 
modelinput = xlsreadm(filepath, range, sheet, "");
Lv=modelinput[.,1];
Lvst=modelinput[.,2];
rcnt=modelinput[.,3];
type_idbeta=packr(modelinput[.,4]);
type_restr=packr(modelinput[.,5]);
endif;

rcntVAR={1,2,4,2,1,2,3,3,4,4,3,3,4,1,2,3,3,2,1,1,1,2,3,3,3,2}; /** # of cointegrating vectors of VAR **/

indxef=indexcat(yyd2,1); /** index position for end of estimation window **/

/*** Forcast Horizon ***/

fhorz=rows(yqrtnumb)-indxef; 
/**********************/


let string titlcvnamad={"h", "T+h","Variable", "Country", "Model","Actual Data"};
nulstr={""};


jf=1;
do while fhorz>0;

if (jf%frq)==1;
forc_index=1;
YdatesFH=yqrtnumb[rows(yqrtnumb)-fhorzorg+1:rows(yqrtnumb),1];
str_yr_forc=YdatesFH[jf]-nyrs_rwin;

{type_wghts,st_yr_fw,rgshmtx_allyrs_filt}=rgshmtx_sc(yr_sq_org,rgshmtx_allyrs_org,nyrs_rwin,forc_index,str_yr_forc);
rgshmtx_allyrs=rgshmtx_allyrs_filt;

endif;


ii=1; /*** estimated window ***/
do while ii<=rows(BeginDates);

startdatef=BeginDates[ii];

yyd1= yqrts[.,1] .$== startdatef;

indxsf=indexcat(yyd1,1); /** index position for start of estimation window **/

if (type_win==2 and jf>1);
indxsf=indxsf+(jf-1);
endif;
 

yr1="" $+ ftocv(yqrtnumb[indxsf,1],1,0); 
qrt1="" $+ ftocv(yqrtnumb[indxsf,2],1,0); 

yr2="" $+ ftocv(yqrtnumb[indxef,1],1,0); 
qrt2="" $+ ftocv(yqrtnumb[indxef,2],1,0); 

/***********************************/


datesH=yqrts[rows(yqrtnumb)-indxef:rows(yqrtnumb)];
indxyy=indxef;
zercol=zeros(rows(yqrts),1);
zercol[indxsf:indxef]=ones((indxef-(indxsf-1)),1);

T=(indxef-(indxsf-1));
startdate_prd=yqrtnumb[indxsf,1];
findate=yqrtnumb[indxef,1];
yr_sq=seqa(startdate_prd,1,findate-startdate_prd+1);
qini=yqrtnumb[indxsf,2];
qfin=yqrtnumb[indxef,2];



newrowsx=vec(zercol .* ones(rows(zercol),N)); 


xnew=xorg[indexcat(newrowsx,1),.];
x=xnew;


/***Constructs the star variables including oil***/

{cc_xstar,zstr}=star_variables(T,N,namvri,id1,k,x,vcex,qini,qfin,frq,yr_sq,rgshmtx_allyrs);

xstr=cc_xstar[.,2:cols(cc_xstar)];


if (type_wghts==2 and type_idbeta/=0);
print"";
print "Options 1 and 2 should be used with the fixed weights option.";
print "Please run the gvar program again selecting the fixed weights"; 
print "option at the beginning of the program";
print"";
stop;
endif;

let string vnamurst={"ys", "ps" , "eqs", "e*", "rs", "lrs", "poil","eps"};
let string starstr={"ys","Dps","eqs","eps","rs","lrs","poil"};
let string dstarstr={"dys", "dDps", "deqs", "deps", "drs", "dlrs", "dpoil"}; 

if type_idbeta==0;
let string vnam={"GDP", "INFL", "EQUITY", "EP", "IR", "LIR", "POIL"};
let string vnamur={"y", "p" , "eq", "e", "r", "lr", "poil","ep"};
let string endstr={"y","Dp","eq","ep","r","lr","poil"};
let string dendstr={"dy","dDp","deq","dep","dr","dlr","dpoil"};  
elseif type_idbeta==1;
let string vnam={"GDP", "INFL", "EQUITY", "EPEPSUS", "IR", "LIR", "POIL"};
let string vnamur={"y", "p" , "eq", "e", "r", "lr", "poil","epepsus"};
let string endstr={"y","Dp","eq","epepsus","r","lr","poil"};
let string dendstr={"dy","dDp","deq","d(epepsus)","dr","dlr","dpoil"};  
elseif type_idbeta==2;
let string vnam={"GDP", "INFL", "EQUITY", "EPEPS", "IR", "LIR", "POIL"};
let string vnamur={"y", "p" , "eq", "e", "r", "lr", "poil","epeps"};
let string endstr={"y","Dp","eq","epeps","r","lr","poil"};
let string dendstr={"dy","dDp","deq","depeps","dr","dlr","dpoil"};  
endif;


{retinfo}=info(startdate_prd,startdate_trdmtx,findate,qini,qfin,frq,nyrs_rwin,type_wghts,
type_idbeta,st_yr_fw,cs);



/***************/


{ccfxend,ccfxstr,zzun}=NominalToRealFX(id1,k,kst,x,xstr,namvri,type_idbeta);


fxend=ccfxend[.,2];
fxstr=ccfxstr[.,2];


/*** Setting domestic and star variables and binary matrices for unit root tests ****/


if k>=4;
namvriur=namvri|99;   /** 99 is the code for es-ps **/ 
else;
namvriur=namvri;
endif;

{binend,binfex,binefe}=endstr_binary_befur(id1,T,k,kst,zzun,namvri,namvriur);


/** setting endogenous- foreign(star) variables (replacing the price level with inflation and e with e-p)
 and binary matrices after unit root tests **/

{zzun1,binend,binfex,binefe}=endstr_binary_aftur(x,namvri,fxend,fxstr,xstr,N,T,k,kst,id1,zstr);


if (ij>NumbExp);
goto label1;
endif;


Tn=(rows(zzun1)/N);


/*** Used for the reposition of the beta's in the case of
 structrural impulse response analysis ***/
 
namvri_org=namvri;       
binefe_org=binend~binfex[.,2:cols(binfex)];


/*****************/

cc_Lv=id1~Lv;
cc_Lvst=id1~Lvst;
cc_nbcoint=id1~rcnt;
cc_nbcointVAR=id1~rcntVAR;


N=rows(id1);


 cv_rep=1; /*** Keeps the countries in the same order, does not perform any reordering **/

if  cv_rep==2;

{id1_rep,cnam_rep,vnam_rep,namvri_rep,binend_rep,binfex_rep,binefe_rep,zzun1_rep,
zstr_rep,endstr_rep,dendstr_rep,starstr_rep,dstarstr_rep,cctorep}=rep_sid(cnam,vnam,id1,k,binend,binfex,namvri,zzun1,zstr,endstr,dendstr,starstr,dstarstr);

cnam=cnam_rep;
vnam=vnam_rep;
namvri=namvri_rep;
binend=binend_rep;
binfex=binfex_rep;
binefe=binefe_rep;
zzun1=zzun1_rep;
zstr=zstr_rep;
endstr=endstr_rep;
dendstr= dendstr_rep;
starstr=starstr_rep;
dstarstr=dstarstr_rep;

/*** repositions fxend & fxstr ***/

ccfxend_rep=reposition(id1_rep,ccfxend,1);
ccfxstr_rep=reposition(id1_rep,ccfxstr,1);

fxend=ccfxend_rep[.,2];
fxstr=ccfxstr_rep[.,2];

/***********************************/

endif;



if  cv_rep==1;
cctorep=0;
endif;


{vk1,vk2,vk1k2,wi,rgshmtx_allyrs_rep,wyear}=link_matricesW(N,T,k,kst,namvri,binend,binfex,zzun1,fxend,fxstr,yr_sq,rgshmtx_allyrs,
                                                                   frq,qini,qfin,id1,cv_rep,cctorep,type_wghts,type_idbeta);


/*** rgshmtx_allyrs_rep is repositioned only of the countries
are re-shuffled else it follows the initial ordering ***/

rgshmtx_allyrs=rgshmtx_allyrs_rep;   


if cv_rep==2;

id1=id1_rep;

{cc_Lvrep}=reposition(id1,cc_Lv,1);
Lv=cc_Lvrep[.,2];

{cc_Lvstrep}=reposition(id1,cc_Lvst,1);
Lvst=cc_Lvstrep[.,2];

{cc_rcntrep}=reposition(id1,cc_nbcoint,1);
rcnt=cc_rcntrep[.,2];

{cc_rcntrepVAR}=reposition(id1,cc_nbcointVAR,1);
rcntVAR=cc_rcntrepVAR[.,2];


if type_idbeta==1;
hdOR_epepsus_rep=reposition_string(cnam,hdOR_epepsus,1);
hdOR_epepsus=hdOR_epepsus_rep;
elseif type_idbeta==2;
hdOR_epeps_rep=reposition_string(cnam,hdOR_epeps,1);
hdOR_epeps=hdOR_epeps_rep;
endif;


endif;


/*** Solving the GVAR ***/

btstrp=1;  /*** Setting it to 1 rather than 0 deactivates all the questions **/
btstrp_sb=-9999; /** bootstapping indicator for structural break tests, these are bootstrapped separately **/

out_ECMVARX=0; 
out_corrVARX=0; 
print_VARX=0;

{covreswm,Gwm,Gdtwm,GBefwm,Greswm,F,betawm,mxpq,Pg,type_id,S0,S1,ChisqDf,LogLik,errcd,errcd_sb,
kpres1,kpres2,nyres1,nyres2,chres1,chres2,chres3,bkdate,rchres1,rchres2,rchres3}=solve_gvar(zzun1,id1,Lv,
Lvst,rcnt,cs_id1,binend,binfex,namvri,cnam,vnam,k,kst,wi,yr_sq,qini,qfin,frq,endstr,dendstr,starstr,
dstarstr,out_ECMVARX,ccut,btstrp,btstrp_sb,namvri_org,binefe_org,cv_rep,type_idbeta,ccOR,print_VARX,
out_corrVARX,hdOR_epepsus,hdOR_epeps,type_restr);


/****** Eigenvalues ******/


{geig,modeig}=eigGVAR(F);

screen off;
print"";
print"";
print"***********************************************************";
print "    Moduli of Eigenvalues of GVAR in decending order";
print"***********************************************************";
print modeig;
print"";
screen on;


/******

/**** Calculation of country and regional PPP-GDP weights ****/

/** PPP-GDP Country Weights - For each variable (gdp,equity, etc) the 
weights are reweighted if for some country that variable does not exist ***/


{cwgts,callvindcwgts,cindvallcwgts}=country_weights(ypp1,binend,namvri); 

cwgts=missrv(cwgts,99999);
vls=reshape(error(0),9,1);
vls[2]=99999;
let string hdcw1={"Country Weights Calculated Using PPP-GDP Figures for 1999-2001"};
let string hdcw2={"Regional Weights Calculated Using PPP-GDP Figures for 1999-2001"};
nulcw1=reshape("",cols(cwgts),2);
nulcw1[2,1]=hdcw1;
fname ="c:\\gauss6.0\\gvar\\output\\cwgts.xls";
ret = xlsWrite(cwgts, fname,"a5",1,vls);
fname ="c:\\gauss6.0\\gvar\\output\\cwgts.xls";
ret = xlsWrite(cnam, fname,"a5",1,"");
fname ="c:\\gauss6.0\\gvar\\output\\cwgts.xls";
ret = xlsWrite(nulcw1'$|("Country"$|vnam)', fname,"a2",1,"");


/****** PPP-GDP Regional Weights *****/


{rgwgts,callvindrgwgts,cindvallrgwgts}=regional_weights(indxregcir,ypp1,binend,namvri);

nulcw2=reshape("",cols(rgwgts),2);
nulcw2[3,1]=hdcw2;
fname ="c:\\gauss6.0\\gvar\\output\\rgwgts.xls";
ret = xlsWrite(rgwgts, fname,"a5",1,vls);
fname ="c:\\gauss6.0\\gvar\\output\\rgwgts.xls";
ret = xlsWrite(cnam, fname,"b5",1,"");
fname ="c:\\gauss6.0\\gvar\\output\\rgwgts.xls";
ret = xlsWrite(nulcw2'$|("Regional #"$|"Country"$|vnam)', fname,"a2",1,"");
/********************************/

*******/


/****%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%****/
if type_wghts==1;
e_fw=(rgshmtx_allyrs[.,1] .eq st_yr_fw);
rgshmtx_rep=selif(rgshmtx_allyrs,e_fw);
else;
rgshmtx_rep=rgshmtx_allyrs;
endif;


/** In case one wants to use the weights for forecasting ***/
ew=(rgshmtx_allyrs_rep[.,1] .eq wyear);
rgshmtxwy=selif(rgshmtx_allyrs_rep,ew);
rgshmtxf=rgshmtxwy[.,2:cols(rgshmtxwy)];

/****%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%****/


/** cvxt_trUSpr: Actual data for the 134 variables transposed that is Txk, where we have p for the US 
and Dp for the rest of the countries with zero for all countries for 1979Q1 except for p US ***/

{cvxforcUSpr,cvxforcUSinfl}=UnCondForc(cs,binend,Gdtwm,GBefwm,cvxt_trUSpr_ini,cvxt_trALLpr_ini,indxyy,fhorz,type_fx);


/** Reposition the variables to following the ordering we want for the output of the forecasts 
and the trasform to growth rates ***/ 

{cvxforcUSinfl_rep}=reposition(id1forc,cvxforcUSinfl,1);
{cvxforcUSinfl_callvind}=callvindforc(namvri,cvxforcUSinfl_rep,1);

label1:

/*** Actual data for the out of sample forecast period, this was repositioned at the beginning
so that the countries follow the desired ordering for the forecast output. We then make the tranformation
to growth rates for all variables except the interest rates and DE=DEP+DP  ***/

cvxt_trUSinfl_callvind_FH=cvxt_trUSinfl_callvind[.,1:2]~cvxt_trUSinfl_callvind[.,2+indxyy+1:cols(cvxt_trUSinfl_callvind)];


if (ij==(NumbExp+1) or ij==(NumbExp+2));

ARorder=1; 

{bcoef}=ARestm(ARorder,binend,zstr,type_fx,ij,NumbExp);

{cvxforcUSinfl_AR}=UnCondForcAR1(ARorder,binend,bcoef,cvxt_trUSinfl,indxyy,fhorz,ij,NumbExp);

/*** AR(1) with constant only or constant plus trend***/

{cvxforcUSinfl_AR_rep}=reposition(id1forc,cvxforcUSinfl_AR,1); 
{cvxforcUSinfl_AR_callvind}=callvindforc(namvri,cvxforcUSinfl_AR_rep,1);

cvxforcUSinfl_callvind=cvxforcUSinfl_AR_callvind;

elseif ij==(NumbExp+3);

/*** For random walk in level no drift ***/

cvxforcUSinfl_rwnd_callvind=cvxt_trUSinfl_callvind[.,1:2]~
(cvxt_trUSinfl_callvind[.,(2+indxyy)] .* ones(rows(cvxt_trUSinfl_callvind),(cols(cvxt_trUSinfl_callvind_FH)-2)));

cvxforcUSinfl_callvind=cvxforcUSinfl_rwnd_callvind;


elseif ij==(NumbExp+4);

/*** For random walk with drift ***/

{driftmu}=drift_rw(binend,zstr,type_fx);

cvxforcUSinfl_rwwd=(seqa(1,1,cols(cvxt_trUSinfl_callvind_FH)-2)' .* (driftmu .* ones(rows(driftmu),(cols(cvxt_trUSinfl_callvind_FH)-2))));

cvxforcUSinfl_rwwd=cvxt_trUSinfl[.,1:2]~(cvxforcUSinfl_rwwd+cvxt_trUSinfl[.,2+indxyy]);

{cvxforcUSinfl_rwwd_rep}=reposition(id1forc,cvxforcUSinfl_rwwd,1); 
{cvxforcUSinfl_rwwd_callvind}=callvindforc(namvri,cvxforcUSinfl_rwwd_rep,1);

cvxforcUSinfl_callvind=cvxforcUSinfl_rwwd_callvind;

endif;


if ii==1;
forcrmse=cvxt_trUSinfl_callvind_FH | cvxforcUSinfl_callvind;
elseif ii>1;
forcrmse=cvxforcUSinfl_callvind;
endif;


datesforc=yqrts2tr[indxyy+1:rows(yqrts2tr)];

{retforcii}=reshapeforc(forcrmse[.,3:cols(forcrmse)],datesforc,fhorz,cvxforcUSinfl_callvind[.,1:2],ii);

if ii==1;
retforc=retforcii;
elseif ii>1;
retforc=retforc~retforcii;
endif;


if jf==1;
ii_str=("" $+ ftocv(ii,1,0));
strwin=(yr1 $+ "Q" $+ qrt1);
namwin=("W" $+ ii_str $+ " :" $+ strwin);
nulstr=nulstr $|namwin;
endif;


ii=ii+1;
endo;


if jf==1;
retforcjf=retforc;
elseif jf>1;
retforcjf=retforcjf|retforc;
endif;


indxef=indxef+1;
fhorz=fhorz-1;
jf=jf+1;
endo;


nulstr1=(nulstr[2:rows(nulstr)])';
titl=titlcvnamad' $~ nulstr1;

/*** step of forecast/date of forecast step/variable/country/model ***/
retforcjf1=retforcjf[.,1:2 4]~retforcjf[.,3]~reshape(ij,rows(retforcjf),1)~retforcjf[.,5:cols(retforcjf)];


if sqij[ij]==ij;
fname ="c:\\gauss6.0\\gvar\\output\\forecast\\xforc_2005Q4.xls";
ret = xlsWrite(retforcjf1, fname,"a2",ij,"");
fname ="c:\\gauss6.0\\gvar\\output\\forecast\\xforc_2005Q4.xls";
ret = xlswritesa(titl, fname,"a1",ij,"");
endif;

marray = putarray(marray,ij,retforcjf1);


ij=ij+1;
endo;



/*** Defined for exporting the RMSFE tables ***/
sumki=sumc(sumc(binend[.,2:cols(binend)]));

sqtabls1=seqa(1,rows(binend),6);
sqtabls2=seqa(rows(binend),rows(binend),5)|sumki;
/********************************/

m1 = getmatrix(marray,1);
totnmbmdls=(NumbExp+numbBM);

/***********/

if type_fx==1;
let string varforc={"Output","Inflation","Real_Equity", "RealFX", 
"ShortTerm_IR", "LongTerm_IR", "OilPrice"};  
else;
let string varforc={"Output","Inflation","Real_Equity", "NominalFX", 
"ShortTerm_IR", "LongTerm_IR", "OilPrice"};  
endif;

binend_forc=reposition(id1forc,binend,1);


Numbfhorz=4; /*** Number of forecast horizons that we want to calculate RMSFE for ***/

jjf=1;
do while jjf<=Numbfhorz;

indcount=0;

cvarray = arrayinit(sumki|((NumbExp*rows(BeginDates))+1)|1,-9999);


jjv=1;
do while jjv<=rows(namvri);

id1forc_new=packr(miss((binend_forc[.,(1+jjv)] .* id1forc),0));

jjc=1;
do while jjc<=sumc(binend_forc[.,(1+jjv)]);

em1=(m1[.,1] .eq jjf);
em2=(m1[.,3] .eq namvri[jjv]);
em3=(m1[.,4] .eq id1forc_new[jjc]);

em=em1 .* em2 .* em3;

subary=marray[.,indexcat(em,1),.];
mm1 = getmatrix(subary,1);

forcstep=mm1[1,1];
varcode=mm1[1,3];
countrycode=mm1[1,4];

h=forcstep;


/***** To use for title in output of tables *****/
namv=varforc[indexcat(namvri,varcode)];
namc=cnamforc[indexcat(id1forc,countrycode)];
forcstp=("" $+ ftocv(forcstep,1,0));

titlrmse=namv $+ namc $+ " (" $+ forcstp $+ " step ahead RMSFE(%))"; 
titlexceed=namv $+ namc $+ " (" $+ forcstp $+ " step ahead Excedeence)"; 
/**************************/


fsvccc=forcstep|varcode|countrycode;

forcM=zeros(rows(mm1),cols(mm1)-(5+1)); 

/*** Computing the GVAR-AveAve forecast ***/

for ja(1,totnmbmdls,1);
mja = getmatrix(subary,ja);
rmsemja=sqrt((sumc((mja[.,6]-mja[.,7:cols(mja)])^2))/rows(mja));
AVErmseWja=sqrt((sumc((mja[.,6]-meanc((mja[.,7:cols(mja)])'))^2))/rows(mja));

if ja==1;
rmseMW=rmsemja';
AVErmseW=AVErmseWja;
elseif ja>1;
rmseMW=rmseMW|rmsemja';
AVErmseW=AVErmseW|AVErmseWja;
endif;

if ja<=totnmbmdls-numbBM;
forcM=forcM+mja[.,7:cols(mja)]; /** numbmodels x numbwin **/
endif;

endfor;

/*** column 7 is the first forecast, column 6 is the actual data ****/

AveforcM=(forcM/(totnmbmdls-numbBM));

AVErmseM=sqrt((sumc((mm1[.,6]-AveforcM)^2))/rows(mm1));
AVEAVErmse=sqrt((sumc((mm1[.,6]-meanc(AveforcM'))^2))/rows(mm1));

ForcMatrix=(rmseMW|AVErmseM')~(AVErmseW|AVEAVErmse);

forcmat=ForcMatrix*100;

Exceed=forcmat[1:NumbExp,1:cols(forcmat)-1] .> forcmat[rows(forcmat),cols(forcmat)];

ExceedBench=forcmat[NumbExp+1:rows(forcmat)-1,1] .> forcmat[rows(forcmat),cols(forcmat)];

NumbExceed=sumc(sumc(Exceed));

LossExceed=(NumbExceed/(rows(modname)*rows(BeginDates)))*100;


let string fmtr = {"%8.16lf"};
forcmatstr=ftostrC(forcmat, fmtr);

Exceedstr=ftostrC(Exceed, fmtr);
ExceedBenchstr=ftostrC(ExceedBench, fmtr);
NumbExceedstr=ftostrC(NumbExceed, fmtr);
LossExceedstr=ftostrC(LossExceed, fmtr);

let string benchnam={"AR1const","AR1const&trend","RW","RWdrift"};

modelnam=modname $| benchnam $| "Ave_m";

winnam="m/w" $~ nulstr1 $~ "Ave_w";

RMSEforcrd=winnam $| (modelnam[1:(rows(modelnam)-(numbBM+1)),.] $~ forcmatstr[1:(rows(modelnam)-(numbBM+1)),.]);

ExceedRMSErd=("m/w" $~ nulstr1)  $| (modelnam[1:(rows(modelnam)-(numbBM+1)),.] $~ Exceedstr);


nulrows=reshape("",3,cols(RMSEforcrd));
nulrows_exceed=reshape("",3,cols(RMSEforcrd)-1);

B1B2Avem=modelnam[rows(modelnam)-(numbBM+1)+1:rows(modelnam),.] $~ forcmatstr[rows(modelnam)-(numbBM+1)+1:rows(modelnam),.];

B1B2AvemAR_RW=B1B2Avem[1:2,.] $| nulrows[1,.] $| B1B2Avem[3:4,.];

RMSEforc = RMSEforcrd $| nulrows[1,.] $| B1B2Avem[rows(B1B2Avem),.] $| nulrows[1,.] $| B1B2AvemAR_RW;

nulrows_exceed1=reshape("",10,cols(RMSEforcrd)-1);

let string NamExceed={"#Exceedence","Exceedence(%)"};

nulrows_exceed1[2:3,1]=NamExceed;

nulrows_exceed1[2:3,2]=NumbExceedstr $| LossExceedstr;

nulrows_exceed1[5:6,2]=ExceedBenchstr[1:2];
let string NamExceedBench1={"#AveAve>AR1const","#AveAve>AR1const&trend"};
nulrows_exceed1[5:6,1]=NamExceedBench1;
let string NamExceedBench2={"#AveAve>RW","#AveAve>RWdrift"};
nulrows_exceed1[8:9,2]=ExceedBenchstr[3:4];
nulrows_exceed1[8:9,1]=NamExceedBench2;

nulrows[2,2]=titlrmse;
nulrows_exceed[2,2]=titlexceed;

RMSEforc=(nulrows $| (RMSEforc $| reshape("",1,cols(RMSEforc))));
ExceedRMSE=(nulrows_exceed $| ExceedRMSErd $| nulrows_exceed1);


colsrmse=cols(RMSEforc);
rowsrmse=rows(RMSEforc);
rows_exceedrmse=rows(ExceedRMSE);
cols_exceedrmse=cols(ExceedRMSE);

indcount=indcount+1;

if jjc==1;
RMSEforc1=RMSEforc;
ExceedRMSE1=ExceedRMSE;
else;
RMSEforc1=RMSEforc1$|RMSEforc;
ExceedRMSE1=ExceedRMSE1$|ExceedRMSE;
endif;


if (jjc==sumc(binend_forc[.,(1+jjv)]) and rows(RMSEforc1)/=(rowsrmse*rows(binend))); 
dif=(rowsrmse*rows(binend))-rows(RMSEforc1);
RMSEforc1=RMSEforc1 $| reshape("",dif,colsrmse);
endif;


if (jjc==sumc(binend_forc[.,(1+jjv)]) and rows(ExceedRMSE1)/=(rows_exceedrmse*rows(binend))); 
difexcd=(rows_exceedrmse*rows(binend))-rows(ExceedRMSE1);
ExceedRMSE1=ExceedRMSE1 $| reshape("",difexcd,cols_exceedrmse);
endif;


jjc=jjc+1;
endo;

if jjv==1;
RMSEforc2=RMSEforc1 $~ reshape("",rows(RMSEforc1),2);
ExceedRMSE2=ExceedRMSE1 $~ reshape("",rows(ExceedRMSE1),2);
else;
RMSEforc2=RMSEforc2$~RMSEforc1 $~ reshape("",rows(RMSEforc1),2);
ExceedRMSE2=ExceedRMSE2 $~ExceedRMSE1 $~ reshape("",rows(ExceedRMSE1),2);
endif;

jjv=jjv+1;
endo;


fname ="c:\\gauss6.0\\gvar\\output\\forecast\\RMSFE_Tables_2005Q4.xls";
ret = xlswritesa(RMSEforc2, fname,"a2",jjf,"");

fname ="c:\\gauss6.0\\gvar\\output\\forecast\\Exceedence_Tables_2005Q4.xls";
ret = xlswritesa(ExceedRMSE2, fname,"a2",jjf,"");


jjf=jjf+1;
endo;


d2 = date;
  et = ethsec(d1,d2);
  et = et/100;
  print "Total elapsed time [mins] :" et/60;
  print "";


end;